import torch
from torch import nn
import torch.nn.functional as F
import torchvision.models as models

from NN.nn_module import NNM
from util.wordnet import *
from util.logger import track_log


class BasicBlock(nn.Module):
    
    def __init__(self, in_planes, planes, stride=1):
        super(BasicBlock, self).__init__()

        self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.shortcut = nn.Sequential()

        if stride != 1 or in_planes != planes:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes)
            )
    
    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += self.shortcut(x)
        out = F.relu(out)

        return out


class ResNet18_WordNet_AUG(NNM):
    loss_log = track_log("output/loss__nopretrained_log.csv").get_logger()
    def module(self):
        self.in_planes = 64
        self.conv1 = nn.Conv2d(self.in_channels, 64, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(64)

        self.layer1 = self._make_layer(BasicBlock, 64, 2, stride=1)
        self.layer2 = self._make_layer(BasicBlock, 128, 2, stride=2)
        self.layer3 = self._make_layer(BasicBlock, 256, 2, stride=2)
        self.layer4 = self._make_layer(BasicBlock, 512, 2, stride=2)

        self.linear1 = nn.Linear(512, 32)

        self.embl1_rule = nn.Linear(512, 256)
        self.embl1_rule1 = nn.Linear(256, 9)

        self.linear2 = nn.Linear(41, self.y_shape)
    
    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        out = F.avg_pool2d(out, 4)
        features = out.view(out.size(0), -1)

        out_label = self.linear1(features)
        
        out_rule1 = F.relu(self.embl1_rule(features))
        # self.out_rule2 = F.softmax(self.embl1_rule1(out_rule1), dim=1)
        self.out_rule2 = self.embl1_rule1(out_rule1)

        label_rule = torch.cat((out_label, self.out_rule2), dim=1) # 32 + 9 = 41
        out_final = self.linear2(label_rule)

        return out_final

    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1] * (num_blocks - 1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes

        return nn.Sequential(*layers)

    def loss_fn(self, y1, y2):
        pred_rule = self.out_rule2
        rule = self.get_rule(y2).to(self.device)

        epsilon = 1e-8
        # pre_rule_log = torch.log(pred_rule + epsilon)
        pre_rule_log = torch.log(torch.softmax(pred_rule, dim=1) + epsilon)

        alpha = 1
        beta = 0.1
        losfnc1 = nn.CrossEntropyLoss()
        loss1 = losfnc1(y1, y2)
        # cross entropy
        loss2 = -torch.sum(rule * pre_rule_log) / rule.shape[0]
        
        loss = alpha * loss1 + beta * loss2
        # self.loss_log.info(f"{loss1.item()}, {loss2.item()}, {loss.item()}, {pred_rule.detach().numpy()}, {rule.detach().numpy()}")
        self.loss_log.info(f"{loss1.item()}, {loss2.item()}, {loss.item()}")
        # self.rule_log.info(f"{pred_rule.detach().numpy()}, {rule.detach().numpy}")
        return loss

    
    def get_rule(self, y):
        batch = torch.Tensor(list(map(lambda x: rule[num_2_class[str(x.item())]], y)))
        return batch

    
